package ivan.cheng.tuqu.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;

/*
 * 文件辅助类
 */
public class FileUtil {

	private static final String NO_CACHE_PATH = "/.nomedia";
	private static FileUtil fileUtils = new FileUtil();

	public static FileUtil getInstance() {
		return fileUtils;
	}

	private FileUtil() {
	}

	
	
	/*
	 * 存储相册图片
	 */
	public synchronized  boolean  savePhotoToDisk( InputStream bmInputStream,
			String fileName) throws FileHandlingException {	 
		boolean bSaveFile=true;
		FileOutputStream outFile = null ;
		try {
			File saveFile = new File(fileName);
		
			 if (saveFile.exists()) {
				 saveFile.delete();
			} 
			outFile = new FileOutputStream(saveFile, true);
			BufferedOutputStream osBuffer=null;
			osBuffer = new BufferedOutputStream(outFile);
			byte[] buf = new byte[1024];
			int len ;		 
		
			while ((len = bmInputStream.read(buf)) > 0) {				
				 // outFile.write(buf, 0, len);	 
				// outFile.flush();	
		 
				osBuffer.write(buf, 0, len);				
			}
			osBuffer.flush();
			outFile.close();
			osBuffer.close();

		} catch (FileNotFoundException e) {
			bSaveFile=false;
			//sError.append("File directory no exist or File Create Error");
			throw new FileHandlingException(e.toString());
		} catch (IOException e) {
			bSaveFile=false;
		
			throw new FileHandlingException(e.toString());
		}catch (Exception e) {
			// TODO: handle exception
			bSaveFile=false;
		}
		finally{

			try {
				bmInputStream.close();			
		 	
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		}
		
		return  bSaveFile;
	}
	
	 /**
     * Store image to SD card.
     */
	public boolean storeImageToFile(Bitmap bitmap,String path,CompressFormat format, int quality){
        if(bitmap == null){
            return false;
        }

        File file =  new File(path);
        RandomAccessFile accessFile = null;
        
        ByteArrayOutputStream steam = new ByteArrayOutputStream();
        bitmap.compress(format, quality, steam);
        byte[] buffer = steam.toByteArray();

        try {
            accessFile = new RandomAccessFile(file, "rw");
            accessFile.write(buffer);
        } catch (Exception e) {
            return false;
        }
        
        try {
            steam.close();
            accessFile.close();
        } catch (IOException e) {
            //Note: do nothing.
        	return false;
        }
        
        return true;
    }
	
 
	/**
	 * 检查给定的路径文件是否存在  
	 * @param path 文件路径 
	 */
	public boolean isExistFile( String strFile){
		File f = new File(strFile);
		return f.exists();
	}
	 
	/**
	 * 创建文件目录 
	 * @param path 文件路径 
	 */
	public static void mkdir(String path) {
		File dir = new File(path);
		if (!dir.exists() || !dir.isDirectory()) {
			dir.mkdir();
		}
	}
	/**
	 * 删除文件 
	 * @param fileName文件路径及名称          
	 */
	public void delFile(String fileName) {
		File DelFile = new File(fileName);
		DelFile.delete();
	}
	/**
	 * 删除文件夹里面的所有文件
	 * @param folderPath 文件夹路径 
	 **/
	public void delAllFile(String folderPath) {
		File file = new File(folderPath);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (folderPath.endsWith(File.separator)) {
				temp = new File(folderPath + tempList[i]);
			} else {
				temp = new File(folderPath + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(folderPath + "/" + tempList[i]);// 先删除文件夹里面的文件
			}
		}
	}
	
	/**
	 * 移动文件到指定目录 
	 * @param oldPath  如：/sdcard/.mioshow/
	 * @param newPath  如：/sdcard/.mioshow/
	 * @throws Exception
	 */
	public void moveFile(String oldPath, String newPath) throws Exception {
		copyFile(oldPath, newPath);
		delFile(oldPath);
	}
	
	/**
	 * 复制单个文件 
	 * @param oldPath   原文件路径 如：/sdcard/.mioshow/
	 *@param newPath    复制后路径 如：/sdcard/.mioshow/
	 * @throws Exception
	 */
	public void copyFile(String oldPath, String newPath) throws Exception {
		int byteRead = 0;	
		InputStream inStream =null;
		FileOutputStream fs =null ;
		try {
			File oldfile = new File(oldPath);			
			if (oldfile.exists()&& oldfile.isFile()) { // 文件存在时
				inStream = new FileInputStream(oldPath); // 读入原文件
				fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1024];
				while ((byteRead = inStream.read(buffer)) != -1) {
					fs.write(buffer, 0, byteRead);
				}
				fs.flush();		
			}			
		} catch (Exception e) {
			LogUtil.e("CopyFile  Error= "+e.toString());
		}finally{
			if (fs!=null) {
				fs.close();
			}
			if (inStream!=null) {
				inStream.close();
			}		
		}
	}
	
	/**
	 * 复制文件到指定目录并且让该文件可以被系统的图片浏览器等扫描到
	 * @param oldPath   原文件路径 如：/sdcard/.mioshow/
	 * @param newPath    复制后路径 如：/sdcard/.mioshow/
	 * @param context    可以用来发送广播事件的上下文
	 * 
	 * @return true表示成功,false表示失败出现了异常
	 */
	public boolean CopyAndScannable(String oldPath, String newPath,Context context)
	{
		try {
			copyFile(oldPath, newPath);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		Intent intent = new Intent(android.content.Intent.ACTION_MEDIA_MOUNTED);
		Uri uri = Uri.parse("file://" + Environment.getExternalStorageDirectory());//Uri.fromFile(new File(newPath));
		intent.setData(uri);
		context.sendBroadcast(intent);
		return true;
		
	}
	
	/**
	 * 复制整个文件夹内容
	 * @param oldPath  原文件路径 如：/sdcard/.mioshow/
	 * @param newPath  复制后路径 如：/sdcard/.mioshow/
	 * @throws Exception
	 */
	public void copyFolder(String oldPath, String newPath) throws Exception {
		(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
		File oFile = new File(oldPath);
		String[] file = oFile.list();
		File temp = null;
		for (int i = 0; i < file.length; i++) {		 
			temp = new File(oldPath + file[i]);
			String	coldPath =oldPath + file[i];
			String	cnewPath =newPath + file[i];
			if(temp.isFile()){     
				moveFile(coldPath,cnewPath);		 
			}else if (temp.isDirectory()) {// 如果是子文件夹
				copyFolder(coldPath+"/", cnewPath+ "/" );
			}
		}

	}
	/**
	 * 得到整个文件夹下内容ID
	 * @param oldPath  原文件路径 如：/sdcard/.mioshow/
 
	 * @throws Exception
	 */
	public String  GetFolderID(String sPath)  {
		 
        File file = new File(sPath);    
        // get the folder list    
 
        File[] array = file.listFiles();   
        if (null ==array) {
			return "";
		} 
        String strids = "";
        for(int i=0;i<array.length;i++){    
            if(array[i].isFile()){    
                // only take file name   
            	
            	strids += array[i].getName();  
            	strids+=",";
            }else if(array[i].isDirectory()){    
            	strids +=GetFolderID(array[i].getPath());    
            }    
        }  
       return strids;

	}	
	
	
	/**
	 * 整个文件夹下所有的路径添加到容
	 * @param oldPath  原文件路径 如：/sdcard/.mioshow/ 
	 * @throws Exception
	 */
	public void  GetFolderPathList(String sPath,List<String> mFilePathLst)  {
		 
        File file = new File(sPath);    
        // get the folder list    
        File[] array = file.listFiles();    
        String strPath = "";
        if (array!=null) {		
	        for(int i=0;i<array.length;i++){    
	            if(array[i].isFile()){    
	                // only take file name    
	            	strPath  = array[i].getPath(); 
	            	if (array[i].length()>0) {
	            		mFilePathLst.add(strPath);
	            	}
	            
	             
	            }else if(array[i].isDirectory()){    
	            	GetFolderPathList(array[i].getPath(),mFilePathLst);    
	            }    
	        }   
        }

	}	
	
	
	/**
	 * 根据XML的文件类型和文件名称，判断本地是否存在此文件，无则从服务器下载图片并存储到相应的目录
	 * @param 文件路径   待定
	 * @param 文件名
	 * @return 无
	 * @throws FileHandlingException 
	 **/
	public void  FileToDisk() throws FileHandlingException
	{
//		InputStream inputStream = null;
//		String strFileName = null;
		
	//	savePhotoToDisk(inputStream,strFileName);
	}

	/**
	 * 查看sd卡是否可用
	 * @return
	 */
	public boolean haveSD() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	 /**
	 * 获取sd卡空间大小
	 * @return
	 */
	public long getSDSize() {
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		File file = new File(sdcard);
		StatFs statFs = new StatFs(file.getPath());
		long availableSpare = (long) (statFs.getBlockSize() * ((long) statFs.getAvailableBlocks()/* - 4*/));

		return availableSpare;
	}

	/**
	 * 查看sd卡是否足够文件存储
	 * 
	 * @param context
	 * @param fileSize 需要存储的文件大小
	 * @return
	 */
	public boolean isSDcardSpaceEnough(/*Context context, */long fileSize) {
		if (!haveSD()) {//
			//Toast.makeText(context,
			//		context.getResources().getString(R.string.Toast_no_sdcard),
			//		Toast.LENGTH_LONG).show();
			return false;
		}
		long sdSize =getSDSize();
		
		if((sdSize >> 32) > 0)
		{
			return true;
		}
		
		if(sdSize < fileSize){//
			//Toast.makeText(context, context.getResources().getString(R.string.Toast_no_sdcard_enough), Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}
	
	/**
	 * @函数说明  生成XML文件
	 * @param sResponse 内容
	 * @param sFilePath 文件生成的路径
	 */
	public void WriteXml(String sResponse, String sFilePath) {
		File file = new File(sFilePath);
		try {
			PrintWriter pWriter = new PrintWriter(new FileWriter(file));
			pWriter.print(sResponse);
			pWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * @函数说明 读取XMl文件
	 * @param sFilePath 文件路径
	 * @return 返回读取的内容
	 */
	public String ReadXml(String sFilePath) {
		String sResponse = "" ;
		BufferedReader file = null;

		try {
			file = new BufferedReader(new FileReader(sFilePath));
			String sReadLine = null;
			try {
				while ((sReadLine = file.readLine()) != null) {
					sResponse += sReadLine;

				}
			 
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace(); 
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); 
		}finally{
			try {
				if (file!=null) {
					file.close();
				}			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return sResponse;

	}
	
	private byte [] Bitmap2Bytes( Bitmap bm) {    
	    ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ;    
	    bm. compress( Bitmap. CompressFormat. PNG, 100, baos) ;    
	    return baos. toByteArray ( ) ;    
	   }    

}
